package cn.john.basic.interceptor;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取token
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)) {
            // 拿到登录人
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if(loginTmp != null) {
                // 不为空就是已经登录了,刷新token过期时间
                redisTemplate.opsForValue().set(token, loginTmp, 30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        // 阻止放行
        return false;
    }
}
